<?php

namespace app\manystore\controller\salescenter;

use app\common\controller\ManystoreBase;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

use think\Db;
use app\manystore\Model\UserModel;
use app\manystore\Model\CampusClewConsultantModel;
use app\manystore\Model\ManystoreModel;
use app\manystore\Model\CourseModel;
use app\manystore\Model\TypeModel;
use app\manystore\Model\CampusClass;
use app\manystore\Model\CampusClassCourseArranging;
use app\manystore\Model\CampusClassCourseDate;
use app\manystore\Model\CampusCourseManagement;
use app\manystore\Model\CampusAuditionRecordModel;
use app\manystore\Model\CampusClassDateRecord;

/**
 * 试听接口
 */
class Audition extends ManystoreBase
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $auth = [];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取课程列表
     *
     * @ApiTitle    获取课程列表
     * @ApiMethod   (GET)

     * @ApiParams (name="search_key", type="string", required=false, description="课程名称")

     * @ApiSector   销售中心
     * @ApiReturn   ({
      "code": 1,
      "msg": "获取数据成功",
      "time": "1658058309",
      "data": [
        {
          "id": 3,
          "name": "测试1",//课程名称
          "class_type": 2,//课程类型:1、一对多;2、一对一
          "hour": [
            {
              "name": "按课时收费-名称-1",
              "price": "100.00",
              "type": "课时"
            },
            ......
          ],
          "monthly": [
            {
              "name": "按月收费-名称-1",
              "price": "10000.00",
              "type": "月"
            },
            ......
          ],
          "day": [
            {
              "name": "按天收费-名称-1",
              "price": "300.00",
              "type": "天"
            }
          ],
        }
      ]
    })
     */
    public function getCourseList()
    {
        $param = $this->request->param();

        $list = CampusCourseManagement::field('a.id,c.name,a.class_type,a.hour_status,a.hour,a.monthly_status,a.monthly,a.per_diem_status,a.day')
        ->alias('a')
        ->where(['shop_id' => $this->auth->shop_id])
        ->where(function($query) use ($param){
            if(!empty($param['search_key']))
            {
                $query->where(['c.name' => ['like','%'.$param['search_key'].'%']]);
            }
        })
        ->join('ss_course c','c.id = a.course_id','left')
        ->select();

        foreach ($list as & $value)
        {
          if(!empty($value['hour_status']))
          {
              $hour = unserialize($value['hour']);
              $collect = [];
              foreach ($hour as $v)
              {
                  $collect[] = [
                    'name' => $v['name'],
                    'price' => sprintf("%01.2f", $v['price']),
                    'type' => '课时',
                  ];
              }
              $value['hour'] = $collect;
          }
          else
          {
            $value['hour'] = [];
          }
          
          if(!empty($value['monthly_status']))
          {
              $monthly = unserialize($value['monthly']);
              $collect = [];
              foreach ($monthly as $v)
              {
                  $collect[] = [
                    'name' => $v['name'],
                    'price' => sprintf("%01.2f", $v['price']),
                    'type' => '月',
                  ];
              }
              $value['monthly'] = $collect;
          }
          else
          {
            $value['monthly'] = [];
          }

          if(!empty($value['per_diem_status']))
          {
              $day = unserialize($value['day']);
              $collect = [];
              foreach ($day as $v)
              {
                  $collect[] = [
                    'name' => $v['name'],
                    'price' => sprintf("%01.2f", $v['price']),
                    'type' => '天',
                  ];
              }
              $value['day'] = $collect;
          }
          else
          {
            $value['day'] = [];
          }

          unset($value['hour_status']);
          unset($value['monthly_status']);
          unset($value['per_diem_status']);
          
        }

        return $this->success('获取数据成功','',$list);
    }

    /**
     * 获取班级列表
     *
     * @ApiTitle    获取班级列表
     * @ApiMethod   (GET)

     * @ApiParams (name="search_key", type="string", required=false, description="班级名称")
     * @ApiParams (name="type", type="string", required=false, description="试听类型【1=跟班试听，2=1对1】")
     * @ApiParams (name="course", type="string", required=false, description="课程ID")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1658060352",
          "data": [
            {
              "id": 1,
              "name": "搏击A班",//班级名称
              "class_size": 10,//班级最大人数
              "num": 5,//班级人数
              "teacher": "张老师",//上课老师
              "is_excess":'0',//是否可超额:0=不可;1=可
            }
          ]
        })
     */
    public function getClassList()
    {
        $param = $this->request->param();

        $where = ['a.shop_id' => $this->auth->shop_id];

        if(!empty($param['type']))
        {
          $where['class_type'] = intval($param['type']);
        }

        $list = CampusClass::field('a.id,a.name,a.class_size,a.num,t.username as teacher,a.is_excess')
        ->alias('a')
        ->where(['a.shop_id' => $this->auth->shop_id])
        ->where(function($query) use ($param){
            if(!empty($param['search_key']))
            {
                $query->where(['a.name' => ['like','%'.$param['search_key'].'%']]);
            }
        })
        ->where(function($query) use ($param){
            if(!empty($param['course']))
            {
              $course_id = intval($param['course']);
              $tmp = [];
              $tmp[] = ['like','%,'.$course_id.',%'];
              $tmp[] = ['like','%,'.$course_id];
              $tmp[] = ['like',$course_id.',%'];
              $tmp[] = $course_id;
              $tmp[] = 'or';

              $query->where(['a.course_id' => $tmp]);
            }
        })
        ->join('ss_manystore t','a.teacher_id = t.id','left')
        ->select();

        return $this->success('获取数据成功','',$list);
    }

    /**
     * 根据时间获取排课列表
     *
     * @ApiTitle    根据时间获取排课列表
     * @ApiMethod   (GET)

     * @ApiParams (name="start", type="date", required=false, description="开始时间")
     * @ApiParams (name="end", type="date", required=false, description="结束时间")
     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1658074146",
          "data": [
            {
              "id": 585,//排课ID
              "course_name": "课程2",//课程名称
              "teacher": "张老师",//老师名称
              "class_name": "搏击A班",//班级名称
              "class_time_start": "06:00",//上课时间
              "class_time_end": "07:00",//下课时间
              "start_time": "2022-06-01 06:00-07:00",//上课日期
            }
          ]
        })
     */
    public function getAppointmentList()
    {
        $param = $this->request->param();

        $end = !empty($param['end']) ? strtotime($param['end'].' 23:59:59') : 0;
        $start = !empty($param['start']) ? strtotime($param['start'].' 00:00:00') : time();
        // $start = max($start,time());

        $list = CampusClassCourseDate::field('cd.id,c.name as course_name,t.username as teacher,c2.name as class_name,a.class_time_start,a.class_time_end,a.start_time,a.end_time')
        ->alias('cd')
        ->join('ss_campus_class_course_arranging a','cd.a_id = a.id','left')
        ->join('ss_course c','c.id = a.course_id','left')
        ->join('ss_manystore t','a.teacher_id = t.id','left')
        ->join('ss_campus_class c2','a.class_id = c2.id','left')
        ->where(function($query) use ($start,$end){
            if(!empty($start))
            {
                $query->where('cd.start_time','>=',$start);
            }
            if(!empty($end))
            {
                $query->where('cd.start_time','<=',$end);
            }
        })
        ->order('a.start_time ASC,a.class_time_start ASC')
        // ->fetchSql()
        ->select();
        // echo $list;exit;

        foreach ($list as $key => $value)
        {
            $value['start_time'] = date('Y-m-d',$value['start_time']).' '.$value['class_time_start'].'-'.$value['class_time_end'];
            unset( $value['end_time']);
        }

        return $this->success('获取数据成功','',$list);
    }

    /**
     * 获取试听课程详情
     *
     * @ApiTitle    获取试听课程详情
     * @ApiMethod   (GET)

     * @ApiParams (name="id", type="integer", required=false, description="排课ID【由排课列表返回ID】")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1658062173",
          "data": {
            "id": 585,
            "course_name": "课程2",//课程名称
            "teacher": "张老师",//老师名称
            "class_name": "搏击A班",//班级名称
            "class_time_start": "06:00",
            "class_time_end": "07:00",
            "class_time": "2022-06-01 06:00 - 07:00",//上课时间
            "class_size": 10,//班级容量
            "class_student_count": 0,//在读学员
            "surplus": 10//剩余容量
          }
        })
     */
    public function getAppointmentInfo()
    {
        $id = intval($this->request->param('id'));

        $info = CampusClassCourseDate::field('cd.id,c.name as course_name,t.username as teacher,c2.name as class_name,a.class_time_start,a.class_time_end,a.start_time,a.end_time,c2.class_size')
        ->alias('cd')
        ->join('ss_campus_class_course_arranging a','cd.a_id = a.id','left')
        ->join('ss_course c','c.id = a.course_id','left')
        ->join('ss_manystore t','a.teacher_id = t.id','left')
        ->join('ss_campus_class c2','a.class_id = c2.id','left')
        ->where(['cd.id' => $id])
        ->order('a.start_time ASC,a.class_time_start ASC')
        ->find();

        $info['class_student_count'] = CampusClassDateRecord::where(['date_id' => $info['id'],'status' => 1])->count();
        $info['surplus'] = intval($info['class_size'] - $info['class_student_count']);

        $info['start_time'] = date('Y-m-d',$info['start_time']).' '.$info['class_time_start'].'-'.$info['class_time_end'];
            unset($info['end_time']);

        return $this->success('获取数据成功','',$info);
    }

    /**
     * 创建试听记录
     *
     * @ApiTitle    创建试听记录
     * @ApiMethod   (GET)

     * @ApiParams (name="course_id", type="integer", required=false, description="排课ID【由排课列表返回ID】")
     * @ApiParams (name="student_id", type="integer", required=false, description="学员ID")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": '1',
          "msg": "预约成功",
          "time": "1658070118",
          "data": null
        })
     */
    public function createAuditionRecord()
    {
        $param = $this->request->param();
        $course_id = !empty($param['course_id']) ? intval($param['course_id']) : 0;
        $student_id = !empty($param['student_id']) ? intval($param['student_id']) : 0;


        $info = CampusClassCourseDate::field('cd.id,c.name as course_name,t.username as teacher,c2.name as class_name,a.class_time_start,a.class_time_end,a.start_time,a.end_time,c2.class_size,t.shop_id,a.class_id,a.course_id,a.teacher_id')
        ->alias('cd')
        ->join('ss_campus_class_course_arranging a','cd.a_id = a.id','left')
        ->join('ss_course c','c.id = a.course_id','left')
        ->join('ss_manystore t','a.teacher_id = t.id','left')
        ->join('ss_campus_class c2','a.class_id = c2.id','left')
        ->where(['cd.id' => $course_id])
        ->order('a.start_time ASC,a.class_time_start ASC')
        ->find();

        $student_id = intval($this->request->param('student_id'));

        $student_info = UserModel::get($student_id);

        if(empty($student_info))
        {
            $this->error('请选择要预约的学员');
        }

        if($student_info->follow_uid != $this->auth->id)
        {
            $this->error('你不是该学员的跟进人，没有权限操作');
        }

        if($this->auth->shop_id != $info['shop_id'])
        {
            $this->error('该课程不是本校区课程');
        }

        $cdr_count = CampusClassDateRecord::where(['user_id' => $student_info->id,'date_id' => $info['id'],'status' => ['<>',0]])->count();
        if($cdr_count > 0)
        {
            $this->error('该学员已经预约了本课程');
        }

        $info['class_student_count'] = CampusClassDateRecord::where(['date_id' => $info['id'],'status' => 1])->count();
        $surplus = intval($info['class_size'] - $info['class_student_count']);
        $is_add = true;

        //约课记录
        $date_record = new CampusClassDateRecord;
        $date_record->shop_id = $info['shop_id'];
        $date_record->user_id = $student_info->id;
        $date_record->class_id = $info['class_id'];
        $date_record->date_id = $info['id'];
        $date_record->status = 1;
        $date_record->createtime = time();

        if($surplus <= 0)
        {
            $is_add = false;
            $date_record->status = 0;
        }

        if($is_add)
        {
            $audition_info = new CampusAuditionRecordModel;
            $audition_info->shop_id = $student_info->shop_id;
            $audition_info->clew_id = $student_info->id;
            $audition_info->course = $info['course_id'];
            $audition_info->classes = $info['class_id'];
            $audition_info->audition_time = $info['start_time'];
            $audition_info->teacher = intval($info['teacher_id']);
            $audition_info->class_hour = floor(strtotime($info['end_time']) - strtotime($info['start_time']));
            $audition_info->is_enrol = 1;
            $audition_info->follow_uid = $student_info->follow_uid;
            $audition_info->collect_people = $student_info->collect_people;
            $audition_info->status = 1;
            $audition_info->updatetime = time();
            $audition_info->createtime = time();
            $audition_info->class_course_arranging = $info['id'];
        }


        // 启动事务
        Db::startTrans();
        try
        {
            if($is_add)
            {
                $audition_info->save();
            }
            $date_record->save();

            

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            echo '<pre>';
            print_r($e);
            exit;
            // 回滚事务
            Db::rollback();
            $this->error('预约失败');
        }

        $this->success('预约成功','');
    }

    /**
     * 取消试听预约
     *
     * @ApiTitle    取消试听预约
     * @ApiMethod   (GET)

     * @ApiParams (name="id", type="integer", required=false, description="预约记录ID")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": '1',
          "msg": "取消成功",
          "time": "1658070118",
          "data": null
        })
     */
    public function cancleAuditionRecord()
    {
        $id = intval($this->request->param('id'));
        $info = CampusAuditionRecordModel::get($id);

        if(empty($info))
        {
            $this->error('预约记录不存在'); 
        }

        if($info->follow_uid != $this->auth->id)
        {
            $this->error('你不是该学员的跟进人，没有权限操作'); 
        }

        $info->status = 3;

        // 启动事务
        Db::startTrans();
        try
        {
            $info->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('取消失败');
        }

        $this->success('取消成功','');
    }

    /**
     * 试听反馈
     *
     * @ApiTitle    试听反馈
     * @ApiMethod   (GET)

     * @ApiParams (name="id", type="integer", required=false, description="预约记录ID")
     * @ApiParams (name="content", type="string", required=false, description="反馈内容")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": '1',
          "msg": "提交反馈成功",
          "time": "1658070118",
          "data": null
        })
     */
    public function feedbackAuditionRecord()
    {
        $id = intval($this->request->param('id'));
        $content = $this->request->param('content');

        $info = CampusAuditionRecordModel::get($id);

        if(empty($info))
        {
            $this->error('预约记录不存在'); 
        }

        if($info->follow_uid != $this->auth->id)
        {
            $this->error('你不是该学员的跟进人，没有权限操作'); 
        }

        $info->feedback = $content;

        // 启动事务
        Db::startTrans();
        try
        {
            $info->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('提交反馈失败');
        }

        $this->success('提交反馈成功','');
    }

    /**
     * 获取试听记录
     *
     * @ApiTitle    获取试听记录
     * @ApiMethod   (GET)

     * @ApiParams (name="search_key", type="string", required=false, description="学员姓名/手机号")
     * @ApiParams (name="audition_time_start", type="date", required=false, description="试听时间【开始】")
     * @ApiParams (name="audition_time_end", type="date", required=false, description="试听时间【结束】")

     * @ApiParams (name="status", type="integer", required=false, description="试听状态【1=已预约,2=已体验,3=已取消,4=未到课】")
     * @ApiParams (name="course", type="integer", required=false, description="课程")
     * @ApiParams (name="classes", type="integer", required=false, description="班级")
     * @ApiParams (name="teacher", type="integer", required=false, description="老师")
     * @ApiParams (name="follow_uid", type="integer", required=false, description="跟进人")
     * @ApiParams (name="is_enrol", type="integer", required=false, description="是否报名【0全部,1=否,2=是】")
     * @ApiSector   销售中心
     * @ApiReturn   ({
        'code' : '1',
        'msg' : '获取数据成功',
        'time' : '1657378506',
        'data' : {
              "collector": [{id:1,name:'课程顾问'}],
              "students_source": [{id:1,name:'学员来源'}],
              ......
            }
     * })
     */
    public function getAuditionRecordList()
    {
        $param = $this->request->param();

        $where = [];

        if(!empty($param['audition_time_start']) && !empty($param['audition_time_end']))
        {
            $where['a.audition_time'] = ['between',[strtotime($param['audition_time_start']),strtotime($param['audition_time_end'])]];
        }
        else if(!empty($param['audition_time_start']))
        {
            $where['a.audition_time'] = ['>=',strtotime($param['audition_time_start'])];
        }
        else if(!empty($param['audition_time_end']))
        {
            $where['a.audition_time'] = ['<=',strtotime($param['audition_time_end'])];
        }

        if(!empty($param['status']))
        {
            $where['status'] = intval($param['status']);
        }

        if(!empty($param['course']))
        {
            $where['course'] = intval($param['course']);
        }

        if(!empty($param['classes']))
        {
            $where['classes'] = intval($param['classes']);
        }

        if(!empty($param['teacher']))
        {
            $where['teacher'] = intval($param['teacher']);
        }

        if(!empty($param['follow_uid']))
        {
            $where['follow_uid'] = intval($param['follow_uid']);
        }

        if(!empty($param['is_enrol']))
        {
            $where['is_enrol'] = intval($param['is_enrol'] - 1);
        }


        $list = CampusAuditionRecordModel::field('u.truename as student_name,c.name as course_name,a.audition_time,m.username as teacher,a.status')
        ->alias('a')
        ->join('ss_manystore m','a.teacher = m.id','left')
        ->join('ss_campus_class cc','a.classes = cc.id','left')
        ->join('ss_course c','a.course = c.id','left')
        ->join('ss_user u','a.clew_id = u.id','left')
        ->where($where)
        ->where(function($query) use ($param){
            if(!empty($param['search_key']))
            {
                $query->whereOr(['truename' => ['like','%'.$param['search_key'].'%'],'mobile' => ['like','%'.$param['search_key'].'%'],'standby_contact' => ['like','%'.$param['search_key'].'%']]);
            }
        })
        ->select();

        $this->success('获取数据成功','',$list);
    }

    /**
     * 获取试听记录详情
     *
     * @ApiTitle    获取试听记录详情
     * @ApiMethod   (GET)

     * @ApiParams (name="id", type="string", required=false, description="记录ID")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1658072702",
          "data": {
            "avatar": "/uploads/20220710/6c30a87c415fc011fbdb73978ba43571.jpg",//头像
            "mobile": "",//手机号
            "student_name": "新测试",//学员名称
            "course_name": "测试6",//课程名称
            "audition_time": "2022-07-21 14:40 - 16:40",预约时间
            "teacher": "吴校",//老师
            "status": 1,//状态:1=已预约,2=已体验,3=已取消,4=未到课
            "class_name": "少儿右脑开发",//班级名称
            "class_time_start": "14:40",//上课时间
            "class_time_end": "16:40",//下课时间
            "feedback": null,//反馈内容
            "course_consultant": "小天"//课程顾问
          }
        })
     */
    public function getAuditionRecordInfo()
    {
        $id = intval($this->request->param('id'));

        $where = ['a.id' => $id];

        $info = CampusAuditionRecordModel::field('u.avatar,u.mobile,u.truename as student_name,c.name as course_name,a.audition_time,m.username as teacher,a.status,cc.name as class_name,cca.class_time_start,cca.class_time_end,a.feedback,ccc.truename as course_consultant')
        ->alias('a')
        ->join('ss_manystore m','a.teacher = m.id','left')
        ->join('ss_campus_class cc','a.classes = cc.id','left')
        ->join('ss_course c','a.course = c.id','left')
        ->join('ss_user u','a.clew_id = u.id','left')
        ->join('ss_campus_class_course_arranging cca','a.class_course_arranging = cca.id','left')
        ->join('ss_campus_clew_consultant ccc','u.course_consultant = ccc.id','left')
        ->where($where)
        ->find();

        $info['audition_time'] = date('Y-m-d',$info['audition_time']).' '.$info['class_time_start'].' - '.$info['class_time_end'];

        $this->success('获取数据成功','',$info);
    }


}
